<template>
  <view class="featured-photos">
    <!-- 照片网格 -->
    <scroll-view 
      class="photo-grid-container" 
      scroll-y 
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 加载中状态 -->
      <view class="loading-state" v-if="isLoading && !photos.length">
        <view class="loading-spinner">
          <u-loading-icon size="36" color="#3a8838"></u-loading-icon>
        </view>
        <text>加载中...</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-else-if="!photos.length">
        <view class="empty-icon">⭐</view>
        <text class="empty-text">暂无精选照片</text>
      </view>

      <!-- 照片网格 -->
      <view v-else class="photo-grid">
        <view 
          class="photo-item"
          v-for="photo in photos"
          :key="photo.photoId"
          @click="handlePhotoClick(photo)"
        >
          <image 
            :src="photo.url" 
            mode="aspectFill"
          ></image>
          <view class="photo-info">
            <text class="photo-title">{{ photo.title || '精选照片' }}</text>
            <text class="photo-date">{{ formatDate(photo.uploadTime) }}</text>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="loading-more" v-if="isLoading && photos.length">
        <view class="loading-spinner">
          <u-loading-icon size="24" color="#999"></u-loading-icon>
        </view>
        <text>加载中...</text>
      </view>

      <!-- 没有更多数据 -->
      <view class="no-more" v-if="noMoreData && photos.length">
        <text>没有更多照片了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { getFeaturedPhotos } from '@/api/photo'
import { getImageBlob } from '@/utils/image.js'
import { formatDate } from '@/utils/date'

export default {
  data() {
    return {
      photos: [],
      page: 1,
      pageSize: 20,
      isLoading: false,
      isRefreshing: false,
      noMoreData: false,
      total: 0
    }
  },
  onLoad() {
    this.initData();
  },
  onShow() {
    // 页面显示时刷新数据
    this.onRefresh();
  },
  methods: {
    // 初始化数据
    async initData() {
      this.isLoading = true;
      try {
        await this.loadPhotos();
      } catch(error) {
        console.error('初始化数据失败:', error);
      } finally {
        this.isLoading = false;
      }
    },
    
    // 加载照片
    async loadPhotos(isRefresh = false) {
      // 如果是初始加载，不设置loading状态，由initData统一管理
      const isInitialLoad = !isRefresh && this.photos.length === 0;
      
      if (isRefresh) {
        this.page = 1;
        this.noMoreData = false;
      }
      
      // 如果不是初始加载也不是刷新，且正在加载或已无更多数据，则返回
      if (!isInitialLoad && !isRefresh && (this.isLoading || this.noMoreData)) {
        return;
      }
      
      // 只有在非初始加载时才设置独立的loading状态
      if (!isInitialLoad) {
        this.isLoading = true;
      }
      
      try {
        // 调用精选照片分页API
        const params = {
          current: this.page,
          size: this.pageSize
        };
        
        const result = await getFeaturedPhotos(params);
        const photos = result.data?.records || [];
        this.total = result.data?.total || 0;
        
        // 处理每个照片的URL
        for (const photo of photos) {
          try {
            photo.url = await getImageBlob(photo.photoPath);
          } catch (err) {
            console.error('加载照片失败:', err);
            photo.url = '';
          }
        }
        
        if (isRefresh) {
          this.photos = photos;
        } else {
          this.photos.push(...photos);
        }
        
        this.noMoreData = this.photos.length >= this.total;
        this.page++;
      } catch (error) {
        console.error('加载照片失败:', error);
        // 只有非初始加载的错误才提示
        if (!isInitialLoad) {
          uni.showToast({
            title: '加载照片失败',
            icon: 'none'
          });
        }
      } finally {
        // 只有非初始加载才在这里重置loading状态
        if (!isInitialLoad) {
          this.isLoading = false;
        }
        
        if (isRefresh) {
          this.isRefreshing = false;
        }
      }
    },
    
    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true;
      try {
        await this.loadPhotos(true);
      } catch(error) {
        console.error('刷新数据失败:', error);
      } finally {
        this.isRefreshing = false;
      }
    },
    
    // 加载更多
    loadMore() {
      this.loadPhotos();
    },
    
    // 处理照片点击
    handlePhotoClick(photo) {
      if (photo && photo.photoId) {
        uni.navigateTo({
          url: `/pages/photo/detail?id=${photo.photoId}`
        });
      }
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      return formatDate(new Date(dateString), 'yyyy-MM-dd');
    }
  }
}
</script>

<style>
.featured-photos {
  min-height: 100vh;
  background-color: #f8f8f8;
}

.photo-grid-container {
  height: 100vh;
  padding: 10rpx;
}

.photo-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 5rpx;
}

.photo-item {
  width: calc(33.33% - 10rpx);
  margin: 5rpx;
  aspect-ratio: 1;
  background-color: #fff;
  border-radius: 8rpx;
  overflow: hidden;
  position: relative;
}

.photo-item image {
  width: 100%;
  height: 100%;
}

.photo-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10rpx;
  background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
  color: #fff;
}

.photo-title {
  font-size: 24rpx;
  margin-bottom: 4rpx;
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.photo-date {
  font-size: 20rpx;
  opacity: 0.8;
}

.loading-state, .empty-state {
  padding: 100rpx 0;
  text-align: center;
  color: #999;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  margin-top: 10rpx;
  display: block;
  font-size: 30rpx;
  color: #666;
}

.loading-more, .no-more {
  padding: 30rpx 0;
  text-align: center;
  color: #999;
  font-size: 24rpx;
}

.loading-spinner {
  display: flex;
  justify-content: center;
  margin-bottom: 10rpx;
}
</style> 